/**   
 * @Title: UpdateMagic.java 
 * @Package com.esun.util.magic 
 * @Description: 更新magicNum 
 * @author: City Jiangsy@500wan.com   
 * @date: 2011-12-30 下午5:09:43  
 * Copyright: (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.util.magic;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;

import com.esun.config.Config;
import com.esun.model.UserInfo;
import com.esun.util.log.EDebug;
import com.esun.util.md5.MD5;

/**
 * @ClassName: UpdateMagic
 * @Description: 更新magicNum
 * @author: City Jiangsy@500wan.com
 * @date: 2011-12-30 下午5:09:43
 * 
 */
public class UpdateMagic {
	private Context context;

	private static final String DBNAME = "db_arabbit2"; // 数据库名
	private static final String TABLE_MAGIC = "magic";
	private static final String EVENT = "event";
	private static final String PRODUCT = "product";
	private static final String SERIALNEW = "serialNew";
	private static final String SERIALOLD = "serialOld";

	private static final int send_success = 100000;
	private static final int send_fail = 100001;
	private Handler handler;

	private String magicNumber = Config.NULLMARK;

	public UpdateMagic(Context context) {
		EDebug.o(this, "\n" + " \n" + "============= start update magic =====================================================================" + "\n");
		this.context = context;
		init();
		initHandler();
	}

	private void initHandler() {
		// TODO Auto-generated method stub
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				case send_success:
					EDebug.o(UpdateMagic.this, "msg = success");
					dropOldMagic();
					postMagic();
					break;

				case send_fail:
					EDebug.o(UpdateMagic.this, "msg = fail");
					UserInfo.getUserInfo().setWlanMac(Config.NULLMARK);
					postMagic();
					break;

				default:
					break;
				}
			}

		};
	}

	private void init() {
		// TODO Auto-generated method stub
		if (isHaveOldMagic()) {
			if (isGetMac()) {
				doSend();
			} else {
				postMagic();
			}
		} else {
			isGetMac();
			postMagic();
		}

	}

	private boolean postMsg() {

		HttpPost httpRequest = new HttpPost(Config.MAGIC_ADD);

		List<NameValuePair> params = new ArrayList<NameValuePair>();

		try {

			params.add(new BasicNameValuePair(EVENT, "5"));
			EDebug.o(this, EVENT + " : " + "5");

			params.add(new BasicNameValuePair(PRODUCT, "rabbit"));
			EDebug.o(this, PRODUCT + " : " + "rabbit");

			params.add(new BasicNameValuePair(SERIALNEW, UserInfo.getUserInfo().getWlanMac()));
			EDebug.o(this, SERIALNEW + " : " + UserInfo.getUserInfo().getWlanMac());

			params.add(new BasicNameValuePair(SERIALOLD, magicNumber));
			EDebug.o(this, SERIALOLD + " : " + magicNumber);

			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			EDebug.o(UpdateMagic.this, "EntityUtils.toString(httpResponse.getEntity()) = " + EntityUtils.toString(httpResponse.getEntity()));

			if (EntityUtils.toString(httpResponse.getEntity()) == "100") {
				return true;
			} else {
				return true;
			}

		} catch (Exception e) {
			return false;
		}

	}

	private void doSend() {

		new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				if (postMsg()) {
					Message msg = handler.obtainMessage(send_success, null);
					handler.sendMessage(msg);
				} else {
					Message msg = handler.obtainMessage(send_fail, null);
					handler.sendMessage(msg);
				}
			}
		}.start();
	}

	private void postMagic() {
		EDebug.o(UpdateMagic.this, " do post magic ");
		try {
			new PostMagicInfo(context);
		} catch (Exception e) {
			EDebug.o(this, "【Magic Number 发送失败！！】");
		}
		EDebug.o(UpdateMagic.this, "\n" + "============= update magic end =====================================================================" + "\n" + " \n");
	}

	private boolean isGetMac() {
		if (getMacAddress() == Config.NULLMARK) {
			return false;
		} else {
			UserInfo.getUserInfo().setWlanMac(getMacAddress());
			return true;
		}
	}

	private boolean isHaveOldMagic() {
		SQLiteDatabase db = context.openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		if (isTableExits(TABLE_MAGIC, db)) {
			Cursor cur;
			cur = db.query(TABLE_MAGIC, new String[] { "magic" }, null, null, null, null, null);

			cur.moveToFirst();

			magicNumber = cur.getString(0);
			db.close();
			EDebug.o(UpdateMagic.this, "do have old magic !!!");
			return true;
		} else {
			db.close();
			EDebug.o(UpdateMagic.this, "have no old magic !!!");
			return false;
		}
	}

	private void dropOldMagic() {
		SQLiteDatabase db = context.openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_MAGIC;
		db.execSQL(DROP_TABLE);
		db.close();
		EDebug.o(UpdateMagic.this, "drop table magic is " + isHaveOldMagic());
	}

	private String getMacAddress() {
		String result = Config.NULLMARK;
		try {
			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			EDebug.o(UpdateMagic.this, "mac adress is " + wifiInfo.getMacAddress());
			result = "mac|" + MD5.md5(wifiInfo.getMacAddress());
			EDebug.o(context, "get mac address = " + result);
		} catch (Exception e) {
			// TODO: handle exception
			EDebug.o(context, "获取mac失败");
		}
		return result;
	}

	/**
	 * 判断表是否存在
	 * 
	 * @param tablename
	 * @return true 表存在 ， false 表示不存在
	 * @author Miko
	 */
	private static boolean isTableExits(String tablename, SQLiteDatabase db) {

		boolean result = false;// 表示不存在
		String str = "SELECT COUNT(*) FROM sqlite_master where type='table' and name='" + tablename + "'";
		Cursor c = db.rawQuery(str, null);
		c.moveToFirst();
		int xcount = Integer.parseInt(c.getString(0));
		if (xcount != 0) {
			result = true; // 表存在
		}
		return result;
	}

}
